package com.yn.demo_redis_lock.task;

import com.yn.demo_redis_lock.redis.RedisPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: TestTask
 * @Description:
 * @author: 王胜
 * @date 2021/4/12
 * @Version: 1.0
 **/
@Configuration
@EnableScheduling
public class TestTask {
    @Value("${server.port}")
    public String ip;
    @Autowired
    RedisPool redisUtils;
    @Scheduled(initialDelay = 0,fixedRate = 60*1000*30*30)
    public void test() {
        redisUtils.setList("ips");
    }

    @Scheduled(cron = "*/3 * * * * *")
    public void testTask() {
        String zxip=redisUtils.get("testTask");
        List<String> isonline=redisUtils.getList("ips");
        if(zxip!=null){
            if(isonline.contains(zxip)){//存活
                if(ip.equals(zxip)){
                    System.out.println("当前执行");
                    run();
                }else{
                    System.out.println(zxip+"当前执行");
                }
            }else {
                redisUtils.releaseLock("testTask");
                if(redisUtils.tryLock("testTask",ip,0)){
                    System.out.println("执行ip挂掉执行");
                    run();
                }
            }
        }else{
            System.out.println("无人执行，"+ip+"执行");
            if(redisUtils.tryLock("testTask",ip,0)){
                run();
            }
        }
    }
//    @Scheduled(cron = "*/3 * * * * *")
//    public void testTask() {
//        boolean lock = redisUtils.tryLock("testTask", ip, 0);
//        String testTask = redisUtils.get("testTask");
//        if (ip.equals(testTask)||lock) {
//            Integer i= Integer.valueOf(redisUtils.get("count"));
//            System.out.println("============"+ip+"\t"+i+"获得分布式锁成功=======================");
//            run();
//            //释放锁
//            redisUtils.releaseLock("testTask");
//            System.out.println("============释放分布式锁成功=======================");
//
//        } else {
//            System.out.println("============获得分布式锁失败=======================");
//            System.out.println("============"+testTask+"机器上占用分布式锁，任务正在执行=======================");
//            return;
//        }
//    }

    public void run() {

        System.out.println("执行中"+new Date());
        try {
            Thread.sleep(1000*5 );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行结束"+new Date());

    }
}
